<?php

require __DIR__ . '/vendor/autoload.php';

$pem = file_get_contents("./test.pem");

function SampleClient() {
    // $client = new \Proto\UserServerClient('127.0.0.1:9527', [
    //     'credentials' => Grpc\ChannelCredentials::createInsecure()
    // ]);
    $client = new \Proto\UserServerClient('127.0.0.1:9527', [
        'credentials' => Grpc\ChannelCredentials::createSsl($pem),
        'grpc.ssl_target_name_override' => 'www.zchd.ltd',
    ]);

    $userParams = new \Proto\UserParams();
    $age = new \Proto\Age();
    $age->setAge("18");
    $userParams->setAge($age);
    $name = new \Proto\Name();
    $name->setName('jack');
    $userParams->setName($name);

    list($id, $status) = $client->SaveUser($userParams)->wait();
    var_dump($status, $id->getId());

    $Id = new Proto\Id();
    $Id->setId('1');

    list($userInfo, $status) = $client->GetUserInfo($Id)->wait();
    var_dump($status, $userInfo->getId(), $userInfo->getName(), $userInfo->getAge());
}

function SaveArticle() {
    $client = new Proto\ArticleServerClient('127.0.0.1:9527', [
        'credentials' => Grpc\ChannelCredentials::createInsecure()
    ]);
    // 请求 SaveArticle 方法
    $stream = $client->SaveArticle();

    $articleParam = new Proto\ArticleParam();

    // 写入流数据
    for ($i = 0; $i < 10; $i++) {
        $articleParam->setAuthor((new Proto\Author())->setAuthor('kevin'));
        $articleParam->setTitle((new Proto\Title())->setTitle('title_php_'. $i));
        $articleParam->setContent((new Proto\Content())->setContent('content_php_'.$i));

        $stream->write($articleParam);
    }

    /**
     * 关闭并返回结果
     * @var $aid Proto\Aid
     */
    list($aid, $status) = $stream->wait();

    var_dump($aid->getId());
}

function GetArticleInfo(){
    $client = new Proto\ArticleServerClient('127.0.0.1:9527', [
        'credentials' => Grpc\ChannelCredentials::createInsecure()
    ]);
    // 请求 GetArticleInfo 方法
    $stream = $client->GetArticleInfo((new Proto\Aid())->setId('668'));

    // 获取服务流数据
    $features = $stream->responses();

    /**
     * @var $feature Proto\ArticleInfo
     */
    foreach ($features as $feature) {
        echo $feature->getId() . '--' . $feature->getAuthor() . '--' .$feature->getTitle() . "--" . $feature->getContent() . PHP_EOL;
    }
}

function DeleteArticle()
{
    $client = new Proto\ArticleServerClient('127.0.0.1:9527', [
        'credentials' => Grpc\ChannelCredentials::createInsecure(),
    ]);
    // 请求 DeleteArticle 方法
    $stream = $client->DeleteArticle();

    $aidParam = new Proto\Aid();
    // 循环流式写入数据
    for ($i = 0 ; $i < 6 ; $i++) {
        $aidParam->setId($i);
        $stream->write($aidParam);
    }
    // 写入结束
    $stream->writesDone();

    /**
     * @var $reply Proto\Status
     */
    while ($reply = $stream->read()) {
        var_dump($reply->getCode());
    }
}

DeleteArticle();